﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Money.Interfaces;
using Money.Data;
using One.Web;
using One.Framework;
using One.Web.UI.WebControls;
using Resources;
using One.Framework.Security;

public partial class Admin_EditUser : System.Web.UI.Page
{
    #region fields
    // xem xet co nen giu page hien tai de tra ve cho paging ko
    private IUserService userService;
    private IRoleService roleService;
    private List<Role> roles;
    protected int userId;
    protected User user = null;
    private string redirectUrl = "UserManagement.aspx";

    #endregion

    #region events

    protected void Page_Load(object sender, EventArgs e)
    {
        userService = ServiceFactory.Create<IUserService>();
        roleService = ServiceFactory.Create<IRoleService>();

        GetParams();
        LoadData();
        AddRules();
        if (!IsPostBack)
        {
            UpdateView();
        }
    }

    protected void AddOrUpdate(object sender, EventArgs e)
    {
        if (validationManager.Validate() && WebSession.CurrentUser.IsInRole(RoleType.Administrator))
        {
            int success = 0;
            if (user == null)
            {
                user = new User();
                user.Username = tbUsername.Text;
                user.Email = tbEmail.Text;
                user.Password = EncryptUtility.HashMD5(tbPassword.Text);
                user.FirstName = tbFirstName.Text;
                user.LastName = tbLastName.Text;
                user.Roles = new List<Role>() { new Role() { RoleId = int.Parse(roleList.SelectedValue) } };
                userService.CreateUser(user);
                success = 1;
            }
            else
            {
                user.FirstName = tbFirstName.Text;
                user.LastName = tbLastName.Text;
                user.Roles = new List<Role>() { new Role() { RoleId = int.Parse(roleList.SelectedValue) } };
                userService.UpdateUser(user);
                success = 2;
            }
            Response.Redirect(string.Format("{0}?success={1}", redirectUrl, success));
        }
    }

    #endregion

    #region private functions

    private void GetParams()
    {
        userId = QueryStringUtility.GetInt32("userId", 0);
    }

    private void LoadData()
    {
        try
        {
            if(userId != 0)
                user = userService.GetUserById(userId);
        }
        catch
        {
            user = null;
        }
        roles = roleService.GetRoles();
    }

    private void UpdateView()
    {
        AddRoles();
        (Master as Admin_MasterPage).SelectedTab = "userManagement";
        if (user == null)
        {
            pageTitle.Text = Resources.Strings.AddUser;
            hlChangePassword.Enabled = false;
            btAddOrUpdate.Text = Resources.Strings.Add;
            divUpdatePassword.Visible = false;
        }
        else
        {
            pageTitle.Text = Resources.Strings.UpdateUser;
            tbConfirmPassword.ReadOnly = tbPassword.ReadOnly = true;
            hlChangePassword.Enabled = true;
            btAddOrUpdate.Text = Resources.Strings.Update;
            divAddPassword.Visible = false;
            roleList.SelectedValue = user.Roles[0].RoleId.ToString();

            tbUsername.Text = user.Username;
            tbEmail.Text = user.Email;
            tbFirstName.Text = user.FirstName;
            tbLastName.Text = user.LastName;
            tbUsername.ReadOnly = tbEmail.ReadOnly = true;
        }
        hlChangePassword.NavigateUrl = string.Format("{0}userId={1}", hlChangePassword.NavigateUrl, user != null ? user.UserId : 0);
    }

    private void AddRoles()
    {
        roleList.DataSource = roles;
        roleList.DataTextField = "Name";
        roleList.DataValueField = "RoleId";
        roleList.DataBind();

        roleList.SelectedIndex = 0;
    }

    private void AddRules()
    {
        validationManager.AddRule(new ValueRequiredRule(tbFirstName, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
        validationManager.AddRule(new ValueRequiredRule(tbLastName, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));

        if (user == null)
        {
            validationManager.AddRule(new ValueRequiredRule(tbUsername, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
            validationManager.AddRule(new PatternMatchedRule(tbUsername, "[a-zA-Z0-9_]+", true, Strings.PatternMatchedErrorMessage, Strings.PatternMatchedHint + " " + "[a-zA-Z0-9_]"));
            validationManager.AddRule(new ValueRequiredRule(tbEmail, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
            validationManager.AddRule(new ValueRequiredRule(tbPassword, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
            validationManager.AddRule(new ValueRequiredRule(tbConfirmPassword, Strings.RequiredFieldErrorMessage, Strings.RequiredFieldHint));
            validationManager.AddRule(new CustomeValidatorRule(tbUsername, Strings.UsernameExistedInDatabaseErrorMessage, Strings.UsernameExistedInDatabaseHint, UsernameValidatator));
            validationManager.AddRule(new StringCompareRule(tbConfirmPassword, tbPassword, Resources.Strings.PasswordUnmatchErrorMessage, Strings.PasswordUnmatchHint));
            validationManager.AddRule(new CustomeValidatorRule(tbEmail, Strings.EmailExitedInDatabaseErrorMessage, Strings.EmailExistedInDatabaseHint, EmailValidatator));
        }

        validationManager.Notifier = new BalloonNotifier();
    }

    private void UsernameValidatator(string username, out bool isValid)
    {
        try
        {
            User userValidate = userService.GetUserByUsername(username);
            isValid = userValidate == null;
        }
        catch
        {
            isValid = true;
        }
    }

    private void EmailValidatator(string email, out bool isValid)
    {
        try
        {
            User userValidate = userService.GetUserByEmail(email);
            isValid = (userValidate == null) || (user != null && userValidate.UserId == user.UserId);
        }
        catch
        {
            isValid = true;
        }
    }

    #endregion

    #region public functions



    #endregion
}
